// packageA/pages/setEquipmentFence/setEquipmentFence.js
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //围栏选择框
    showFence:false,
    //围栏选择数据
    fenceList:[],
    //围栏id
    fenceId:null,
    //围栏名字
    fenceName:'',
    //端口
    port:null,
    //显示选择人员
    showUser: false,
    //人员列表
    userList: [],
    //无数据
    showNothing: false,
    //已选中人员
    listMap: null,
    //已选中人员数组
    selectUser: [],
    //已选中人员id
    recipient: [],
    //已选中人员姓名
    recipientNames: []  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      listMap: new Map()
    })

    if(options.paramObj){      
      let paramObj=JSON.parse(options.paramObj);
      console.log('设备围栏传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      //查询port
      this.getPort(paramObj.imei);

      //围栏名称回显
      if(paramObj.fenceId){
        this.setData({
          fenceId: paramObj.fenceId
        })
        this.getFenceInfo(paramObj.fenceId);
      }

      //人员回显
      if(paramObj.recipient){
        let sList=paramObj.recipient;
        let listMap=this.data.listMap;
        let ids=[],names=[];

        sList.forEach(item => {
          ids.push(item.id);
          names.push(item.nickName);
          listMap.set(item.id,item);
        });


        this.setData({
          selectUser: sList,
          listMap: listMap,
          recipient: ids,
          recipientNames: names
        })
      }
    }
  },

  //查询port
  getPort(imei){
    let param={
      imei: imei
    }

    CommonService.goFindOneByImei(param).then(res=>{
      if(res.data.data.result && res.data.data.result.port){
        this.setData({
          port: res.data.data.result.port,
          serviceAddress: res.data.data.result.localAddress
        })
      }
    }).catch((error) => {
    })
  },

  //获取围栏名称
  getFenceInfo(id){
    let param = {
      isAuth: true,
      className: 'equipmentFence',
      data: {
        id:id,
        selectFields: ['id', 'name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        this.setData({
          fenceName: result.name
        })
      }
    }).catch((error) => {
    })
  },

  //显示围栏选择框
  onShowFence(){
    this.setData({
      showFence: true 
    })
    this.getFenceList();
  },

  //查询围栏
  getFenceList(){
    let param = {
      isAuth: true,
      className: 'equipmentFence',
      data: {
        searchAll: true,
        selectFields: ['id', 'name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          fenceList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏围栏选择框
  onCloseFence(){
    this.setData({
      showFence: false
    })
  },

  //确认围栏
  onConfirmFence(e){
    this.setData({
      fenceId:e.detail.value.id,
      fenceName:e.detail.value.text
    })
    this.onCloseFence();
  },

  //设置围栏
  onSetFence(){
    //围栏必填
    if(!this.data.fenceId){
      Toast.fail('请设置围栏');
      return;
    }

    //人员必填
    if(!this.data.recipient.length){
      Toast.fail('请选择提醒人员');
      return;
    }
    
    let port=this.data.port;
    let address=this.data.serviceAddress;

    if(address=='47.99.141.227'){
      port=88800;
    }

    let obj=this.data.paramObj;
    let param = {
      imei: obj.imei,
      fenceId: this.data.fenceId,
      port: port,
      recipient: this.data.recipient
    }

    console.log(param);
    return;

    CommonService.setFence(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('设置成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);

      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //显示人员
  onShowUser(){
    this.setData({
      showUser: true 
    })
    this.getUserList();
  }, 

  //隐藏人员
  onCloseUser(){
    this.setData({
      showUser: false
    })
  },

  //获取人员列表
  getUserList(){
    let param={
      imei: this.data.paramObj.imei
    };  

    CommonService.findRecipient(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.user && res.data.data.result.user.length) {
        let result=res.data.data.result.user;

        //去掉已选人员
        let userList=[];
        let listMap=this.data.listMap;

        if(listMap.size){
          result.forEach(item => {
            if(!listMap.has(item.id)){
              userList.push(item);
            }  
          });
        }else{
          userList=result;
        }  

        this.setData({
          userList: userList
        })   
      }else{
        this.setData({
          showNothing: true
        })
        
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //点击选择人员
  onClickUser({currentTarget}) {
    let detail=currentTarget.dataset.detail;
    let list=this.data.userList;
    let selectUser=this.data.selectUser;
    let listMap=this.data.listMap;
    let arr=[];

    //人员是否绑定微信
    this.isBind(detail.id).then(value => {
      if(value){
        selectUser.push(detail);
        listMap.set(detail.id,detail);

        list.forEach(item => {
          if(item.id!=detail.id){
            arr.push(item);
          }
        });
  
        this.setData({
          userList: arr,
          selectUser: selectUser,
          listMap: listMap,
          disabled: false
        })  
      }else{
        Toast.fail({
          duration: 3000,
          message: detail.nickName+'未绑定微信（个人中心-设置-绑定微信）'
        });
      }
    });  
  },

  //删除选中的人员
  onDeleteUser({currentTarget}){
    let detail=currentTarget.dataset.detail;
    let list=this.data.userList;
    let selectUser=this.data.selectUser; 
    let listMap=this.data.listMap;   
    let arr=[];

    //删除map中数据
    listMap.delete(detail.id);

    //删除已选列表数据，加入人员列表
    selectUser.forEach(item => {
      if(item.id==detail.id){
        list.push(item);
      }else{
        arr.push(item);
      }
    });

    this.setData({
      userList: list,
      selectUser: arr
    })
  },

  //人员是否绑定微信
  isBind(id){
    let param = {
      isAuth: false,
      className: 'wechatLogin',
      data: {
        userId: id,
        selectFields: ['id'],
        nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if(res.data.data && res.data.data.result && res.data.data.result.length){
          resolve(true);
        }else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //确认人员
  onConfirmUser(){
    let sList=this.data.selectUser;
    if(sList.length){
      let ids=[],names=[];
      sList.forEach(item => {
        ids.push(item.id);
        names.push(item.nickName);
      });

      this.setData({
        recipient: ids,
        recipientNames: names
      })

      this.onCloseUser();
    }else{
      Toast.fail('请选择人员');
    }  
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    
    prevPage.setData({
      showButton: false
    })
    prevPage.refreshListAndPage();
    
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})